﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess;
using System.Data;

namespace XuaNhapKho
{
    public partial class NhaCungCap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadGridView();
                loadData();
            }
        }

        private void loadData()
        {
            grvNhaCC.DataSource = NhaCungCapDAO.GetAll();
            grvNhaCC.DataBind();
        }

        private void loadGridView()
        {
            if (Request.QueryString["id"] != null)
            {
                int id = int.Parse(Request.QueryString["id"].ToString());
                DataTable dt = NhaCungCapDAO.GetBy(id).Tables[0];

                foreach (DataRow rows in dt.Rows)
                {
                    txtTenNCC.Text = rows["TenNhaCungCap"].ToString();
                    txtDiaChi.Text = rows["TenNhaCungCap"].ToString();
                    txtDienThoai.Text = rows["DienThoai"].ToString();
                    txtEmail.Text = rows["Email"].ToString();
                    txtWebsite.Text = rows["Website"].ToString();
                }

            }
        }

        protected void lbtnEdit_Command(object sender, CommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());
            Response.Redirect("/NhaCungCap.aspx?id=" + id);
        }

        protected void lbtnRemove_Command(object sender, CommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());
            NhaCungCapDAO.Delete(id);
            Response.Redirect("/NhaCungCap.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string name = txtTenNCC.Text;
            string diachi = txtDiaChi.Text;
            string dienthoai = txtDienThoai.Text;
            string email = txtEmail.Text;
            string website = txtWebsite.Text;

            if (Request.QueryString["id"] == null)
            {
                NhaCungCapDAO.Insert(name, diachi, dienthoai, email, website);
                Response.Redirect("/NhaCungCap.aspx");
            }
            else
            {
                int id = int.Parse(Request.QueryString["id"].ToString());
                NhaCungCapDAO.Update(id, name, diachi, dienthoai, email, website);
                Response.Redirect("/NhaCungCap.aspx");
            }
        }

        protected void grvNhaCC_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvNhaCC.PageIndex = e.NewPageIndex;
            loadGridView();
        }
    }

}